/**
 * Copyright 2018-2020 stylefeng & fengshuonan (https://gitee.com/stylefeng)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.stylefeng.guns.modular.hp.controller;

import cn.stylefeng.guns.config.properties.GunsProperties;
import cn.stylefeng.guns.config.properties.HpProperties;
import cn.stylefeng.guns.core.common.annotion.BussinessLog;
import cn.stylefeng.guns.core.common.constant.factory.PageFactory;
import cn.stylefeng.guns.core.common.node.JsonResult;
import cn.stylefeng.guns.core.common.page.PageInfoBT;
import cn.stylefeng.guns.core.shiro.ShiroKit;
import cn.stylefeng.guns.modular.hp.model.FileDownloadInfo;
import cn.stylefeng.guns.modular.hp.model.PresidentMailInfo;
import cn.stylefeng.guns.modular.hp.service.IFileDownloadInfoService;
import cn.stylefeng.guns.modular.hp.warpper.FileDownloadInfoWrapper;
import cn.stylefeng.roses.core.base.controller.BaseController;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.*;
import java.util.*;

/**
 * 下载专区的控制类
 *
 * @author xzqiang
 * @Date 2019年5月27日
 */
@Controller
@RequestMapping("/hp/file")
public class FileDownloadInfoController extends BaseController {

    private String PREFIX = "/hp/filedown/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private HpProperties hpProperties;

    @Autowired
    private IFileDownloadInfoService fileDownloadInfoService;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "file.html";
    }

    /**
     * 查询下载专区列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String beginTime, @RequestParam(required = false) String endTime, @RequestParam(required = false) String logName, @RequestParam(required = false) Integer logType) {
        Page<PresidentMailInfo> page = new PageFactory<PresidentMailInfo>().defaultPage();
        List<Map<String, Object>> result = fileDownloadInfoService.list();
        page.setRecords(new FileDownloadInfoWrapper(result).wrap());
        return new PageInfoBT<>(page);
    }

    /**
     * 查询院长信箱详情
     */
    @RequestMapping("/file_add")
    public String addFile() {
        String htmlPath = "file_upload.html";
        return PREFIX + htmlPath;
    }

    /**
     * 删除院长信箱
     */
    @RequestMapping("/delete")
    @ResponseBody
    @BussinessLog(value = "删除首页栏目", key = "id")
    public Object del(@RequestParam String id) {
        this.fileDownloadInfoService.deleteById(id);
        return SUCCESS_TIP;
    }

    @RequestMapping(value="/upload", method= RequestMethod.POST)
    @ResponseBody
    public JsonResult handleFileUpload(MultipartHttpServletRequest request){
        JsonResult jr = new JsonResult();
        Iterator<String> iterator = request.getFileNames();
        try{
        while (iterator.hasNext()) {
            String fileName = iterator.next();
            MultipartFile multipartFile = request.getFile(fileName);
            fileName = multipartFile.getOriginalFilename();

                String fileSavePath = gunsProperties.getFileUploadPath();
                File file = new File(fileSavePath);

                if (!file.exists() && !file.isDirectory()) {
                    System.out.println(file + "目录不存在，需要创建");
                    //创建目录
                    file.mkdir();
                }
                //创建一个文件输出流
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(fileSavePath + fileName));
                int length = 0;
                byte[] buffer = new byte[1024];
                InputStream inputStream = multipartFile.getInputStream();
                while ((length = inputStream.read(buffer)) != -1) {
                    stream.write(buffer, 0, length);
                }
                stream.flush();
                stream.close();

                FileDownloadInfo fileDownloadInfo = new FileDownloadInfo();
                fileDownloadInfo.setFilename(fileName);
                fileDownloadInfo.setDownloadUrl("");
                fileDownloadInfo.setFilesize(multipartFile.getSize());
                fileDownloadInfo.setDirPath(fileSavePath + fileName);
                fileDownloadInfo.setCreatedTime(new Date());
                fileDownloadInfo.setCreater(ShiroKit.getUser().getId().toString());
                fileDownloadInfo.insert();

                String fileDownLoadUrl = hpProperties.getFileDownloadPath() + fileDownloadInfo.getId();
                fileDownloadInfo.setDownloadUrl(fileDownLoadUrl);
                fileDownloadInfo.updateById();

                jr.setResultCode(0);
                jr.setResultMsg("文件上传成功！");
        }
        }catch (IOException e){
            jr.setResultCode(1);
            jr.setResultMsg("文件上传失败！");
            e.printStackTrace();
        }
        return jr;
    }

    @RequestMapping(value="/articleFileUpload", method= RequestMethod.POST)
    @ResponseBody
    public JsonResult articleFileUpload(MultipartHttpServletRequest request){
        JsonResult jr = new JsonResult();
        Iterator<String> iterator = request.getFileNames();
        try{
            while (iterator.hasNext()) {
                String fileName = iterator.next();
                MultipartFile multipartFile = request.getFile(fileName);
                fileName = multipartFile.getOriginalFilename();

                String fileSavePath = gunsProperties.getFileUploadPath();
                File file = new File(fileSavePath);

                if (!file.exists() && !file.isDirectory()) {
                    System.out.println(file + "目录不存在，需要创建");
                    //创建目录
                    file.mkdir();
                }
                //创建一个文件输出流
                BufferedOutputStream stream = new BufferedOutputStream(
                        new FileOutputStream(fileSavePath + fileName));
                int length = 0;
                byte[] buffer = new byte[1024];
                InputStream inputStream = multipartFile.getInputStream();
                while ((length = inputStream.read(buffer)) != -1) {
                    stream.write(buffer, 0, length);
                }
                stream.flush();
                stream.close();

                FileDownloadInfo fileDownloadInfo = new FileDownloadInfo();
                fileDownloadInfo.setFilename(fileName);
                fileDownloadInfo.setDownloadUrl("");
                fileDownloadInfo.setFilesize(multipartFile.getSize());
                fileDownloadInfo.setDirPath(fileSavePath + fileName);
                fileDownloadInfo.setTemp(FileDownloadInfo.TEMP_YES);
                fileDownloadInfo.setCreatedTime(new Date());
                fileDownloadInfo.setCreater(ShiroKit.getUser().getId().toString());
                fileDownloadInfo.insert();

                String fileDownLoadUrl = hpProperties.getFileDownloadPath() + fileDownloadInfo.getId();
                fileDownloadInfo.setDownloadUrl(fileDownLoadUrl);
                fileDownloadInfo.updateById();


                Map<String,String> fileMap  = new HashMap<>();
                fileMap.put("fileName",fileDownloadInfo.getFilename());
                fileMap.put("fileId",fileDownloadInfo.getId());

                jr.setResultCode(0);
                jr.setResultMsg("文件上传成功！");
                jr.setResultData(fileMap);
            }
        }catch (IOException e){
            jr.setResultCode(1);
            jr.setResultMsg("文件上传失败！");
            e.printStackTrace();
        }
        return jr;
    }
}
